﻿using Engine;
using Game;
using GameEntitySystem;
using TemplatesDatabase;
using System.Collections.Generic;

namespace SAGhoul
{
    public class SubsystemEdibleItemBehavior : SubsystemBlockBehavior
    {
        public SubsystemAudio m_subsystemAudio;
        public SubsystemTime m_subsystemTime;
        public SubsystemParticles m_subsystemParticles;
        public Game.Random m_random = new();

        // 长按时间阈值（秒）
        public const float HoldTimeRequired = 1.5f;
        private float m_holdTimeElapsed;
        private bool m_isHolding;
        private bool m_hasPlayedHoldSound;
        private float m_swingOffset;
        private float m_swingDirection = 1f; // 控制摆动方向

        public override int[] HandledBlocks => [];

        public override bool OnInteract(TerrainRaycastResult raycastResult, ComponentMiner componentMiner)
        {
            // 获取玩家手中的物品
            int itemValue = componentMiner.ActiveBlockValue;

            // 检查手中是否有物品
            if (componentMiner.Inventory == null) return false;
            int activeSlotIndex = componentMiner.Inventory.ActiveSlotIndex;
            int slotCount = componentMiner.Inventory.GetSlotCount(activeSlotIndex);

            if (slotCount <= 0) return false;

            // 获取食物营养值
            Block block = BlocksManager.Blocks[Terrain.ExtractContents(itemValue)];
            float nutritionalValue = block.GetNutritionalValue(itemValue);

            // 检查是否为食物
            if (nutritionalValue <= 0f) return false;

            // 检查是否满足进食条件
            ComponentVitalStats vitalStats = componentMiner.Entity.FindComponent<ComponentVitalStats>();
            if (vitalStats == null) return false;

            if (vitalStats.Food >= 0.99f)
            {
                return false;
            }

            // 检查是否对同类食物感到厌倦
            vitalStats.m_satiation.TryGetValue(Terrain.ExtractContents(itemValue), out float satiationValue);
            if (satiationValue > 6f)
            {
                componentMiner.ComponentPlayer.ComponentGui.DisplaySmallMessage(LanguageControl.Get(typeof(ComponentVitalStats).Name, "6"), Color.Blue, blinking: true, playNotificationSound: true);
                return false;
            }

            // 开始长按逻辑
            if (!m_isHolding)
            {
                m_isHolding = true;
                m_holdTimeElapsed = 0f;
                m_hasPlayedHoldSound = false;
                m_swingOffset = 0f;
                m_swingDirection = 1f;
            }

            return true;
        }

        public override bool OnAim(Ray3 aim, ComponentMiner componentMiner, AimState state)
        {
            switch (state)
            {
                case AimState.InProgress:
                    {
                        if (componentMiner.Inventory == null) return false;

                        int activeSlotIndex = componentMiner.Inventory.ActiveSlotIndex;
                        int slotValue = componentMiner.Inventory.GetSlotValue(activeSlotIndex);
                        int slotCount = componentMiner.Inventory.GetSlotCount(activeSlotIndex);

                        if (slotCount <= 0) return false;

                        // 获取食物营养值
                        Block block = BlocksManager.Blocks[Terrain.ExtractContents(slotValue)];
                        float nutritionalValue = block.GetNutritionalValue(slotValue);

                        // 检查是否为食物
                        if (nutritionalValue <= 0f) return false;

                        // 检查是否满足进食条件
                        ComponentVitalStats vitalStats = componentMiner.Entity.FindComponent<ComponentVitalStats>();
                        if (vitalStats == null) return false;

                        if (vitalStats.Food >= 0.99f)
                        {
                            ResetHoldState();
                            return false;
                        }

                        // 检查是否对同类食物感到厌倦
                        vitalStats.m_satiation.TryGetValue(Terrain.ExtractContents(slotValue), out float satiationValue);
                        if (satiationValue > 6f)
                        {
                            componentMiner.ComponentPlayer.ComponentGui.DisplaySmallMessage(LanguageControl.Get(typeof(ComponentVitalStats).Name, "6"), Color.Blue, blinking: true, playNotificationSound: true);
                            ResetHoldState();
                            return false;
                        }

                        // 更新摆动偏移量以实现往复抖动效果
                        m_swingOffset += m_swingDirection * 0.05f * m_subsystemTime.GameTimeDelta * 60f;
                        if (m_swingOffset > 0.1f || m_swingOffset < -0.1f)
                        {
                            m_swingDirection *= -1f; // 反转方向
                        }

                        // 设置手部角度
                        componentMiner.ComponentCreature.ComponentCreatureModel.AimHandAngleOrder = 0.9f;

                        // 第一人称视角物品设置
                        ComponentFirstPersonModel componentFirstPersonModel = componentMiner.Entity.FindComponent<ComponentFirstPersonModel>();
                        if (componentFirstPersonModel != null)
                        {
                            componentFirstPersonModel.ItemOffsetOrder = new Vector3(-0.2f + m_swingOffset, 0.35f, 0.17f);
                            componentFirstPersonModel.ItemRotationOrder = new Vector3(-0.5f, 0f, 0f);
                        }

                        // 手持物品设置（同步摆动但幅度较小）
                        componentMiner.ComponentCreature.ComponentCreatureModel.InHandItemOffsetOrder =
                            new Vector3(-0.3f + m_swingOffset * 0.5f, -0.3f, 0f);
                        componentMiner.ComponentCreature.ComponentCreatureModel.InHandItemRotationOrder =
                            new Vector3(2f, 0f, 0f);

                        // 长按计时逻辑
                        if (!m_isHolding)
                        {
                            m_isHolding = true;
                            m_holdTimeElapsed = 0f;
                            m_hasPlayedHoldSound = false;
                        }
                        else
                        {
                            m_holdTimeElapsed += m_subsystemTime.GameTimeDelta;

                            // 修改这里：将0.1f改为0.2f，让音效在0.2秒后播放
                            if (!m_hasPlayedHoldSound && m_holdTimeElapsed >= 0.2f)
                            {
                                m_subsystemAudio.PlaySound("Audio/HumanEat1", 4f, m_random.Float(-0.1f, 0.1f),
                                    componentMiner.ComponentCreature.ComponentCreatureModel.EyePosition, 2.5f, autoDelay: true);
                                m_hasPlayedHoldSound = true;
                            }

                            if (m_holdTimeElapsed >= HoldTimeRequired)
                            {
                                ConsumeItemAndEat(componentMiner, slotValue);
                                ResetHoldState();
                            }
                        }
                        break;
                    }

                case AimState.Completed:
                    ResetHoldState();
                    break;
            }
            return false;
        }

        private void ConsumeItemAndEat(ComponentMiner componentMiner, int itemValue)
        {
            // 添加材质破碎粒子效果
            Vector3 particlePosition = componentMiner.ComponentCreature.ComponentCreatureModel.EyePosition +
                componentMiner.ComponentCreature.ComponentCreatureModel.EyeRotation.GetForwardVector() * 0.5f;

            int textureSlot = BlocksManager.Blocks[Terrain.ExtractContents(itemValue)].GetFaceTextureSlot(0, itemValue);
            BlockDebrisParticleSystem particleSystem = new(
                componentMiner.m_subsystemTerrain,
                particlePosition,
                1.5f,  // 强度
                1.5f,  // 缩放
                Color.LightYellow,
                textureSlot
            );
            m_subsystemParticles.AddParticleSystem(particleSystem);

            componentMiner.RemoveActiveTool(1);

            // 直接从ComponentMiner获取最新的ComponentVitalStats
            ComponentVitalStats vitalStats = componentMiner.Entity.FindComponent<ComponentVitalStats>();

            // 重置该食物的厌倦值，然后再调用Eat方法
            if (vitalStats != null)
            {
                int foodType = Terrain.ExtractContents(itemValue);
                // 重置该食物类型的厌倦值
                vitalStats.m_satiation[foodType] = 0f;
                // 调用正常的Eat方法
                vitalStats.Eat(itemValue);
            }
        }

        private void ResetHoldState()
        {
            m_isHolding = false;
            m_holdTimeElapsed = 0f;
            m_hasPlayedHoldSound = false;
            m_swingOffset = 0f;
            m_swingDirection = 1f;
        }

        public override void Load(ValuesDictionary valuesDictionary)
        {
            m_subsystemAudio = Project.FindSubsystem<SubsystemAudio>(throwOnError: true);
            m_subsystemTime = Project.FindSubsystem<SubsystemTime>(throwOnError: true);
            m_subsystemParticles = Project.FindSubsystem<SubsystemParticles>(throwOnError: true);
            base.Load(valuesDictionary);
        }
    }
}